# -*- coding: UTF-8 -*-
from flask import jsonify,request,make_response
from .. import utils
from .. import MessageAnalysis
from . import api
import os
import base64
import time
from werkzeug.utils import secure_filename
from strUtil import Pic_str
basedir = os.path.abspath(os.path.dirname(__file__))
UPLOAD_FOLDER='upload'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'gif', 'GIF'])
 
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

def dectohex(input):
    input=int(input)
    my_hex=hex(input)
    my_return=my_hex.replace('0x','')
    return my_return

#UTF8 -> GB2312 -> HEX
def utf8_gb2312_hex(input):
    #my_utf8=input.decode('utf8')
    my_gb2312=input.encode('gb2312')
    my_hex=my_gb2312.encode('hex')
    return my_hex

def complete_bite(needbit,input,after='TRUE'):
    needbit=int(needbit)
    input=str(input)
    len_input=len(input)
    completebit=needbit - len_input
    if after == 'FALSE':
        my_return="0"*completebit+input
    elif after == 'TRUE':
        my_return=input+"0"*completebit
    else:
        pass
    return my_return

def ucivdr(config,para):
    para=str(para)
    my_uci_vdr='uci -c /vdr/config/ set vdr.config.'+config+'='+"'"+para+"'"
    return my_uci_vdr

################################## VDR Information ##################################
@api.route('/get_vdr_config/<sn>/')
def get_vdr_config(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/get_vdr_config.sh|sh')
    return jsonify(r)

@api.route('/get_speed_limit/<sn>/')
def get_speed_limit(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/get_speed_limit.sh|sh')
    return jsonify(r)

@api.route('/get_gps_signal/<sn>/')
def get_gps_signal(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/get_gps_signal.sh|sh')
    return jsonify(r)


@api.route('/get_server_status/<sn>/')
def get_server_status(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/get_server_status.sh|sh')
    return jsonify(r)

@api.route('/get_scinfo/<sn>/')
def get_scinfo(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/get_scinfo.sh|sh')
    return jsonify(r)

@api.route('/get_dumptime/<sn>/')    #50
def get_dumptime(sn):
    r=utils.exec_command(sn, 'vcmd dump_time:')
    return jsonify(r)

@api.route('/get_overtime/<sn>/')    #50
def get_overtime(sn):
    r=utils.exec_command(sn, 'hexdump -C /vdr/record/overtime')
    return jsonify(r)

@api.route('/get_tts_vol/<sn>/')    #50
def get_tts_vol(sn):
    r=utils.exec_command(sn, 'cat /vdr/config/vdr |grep tts_vol')
    return jsonify(r)

@api.route('/get_4g_version/<sn>/')    #50
def get_4g_version(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/get_4g_information.sh|sh')
    return jsonify(r)

@api.route('/get_print_log/<sn>/')    #50
def get_print_log(sn):
    r=utils.exec_command(sn, 'cat /tmp/vdr_slip.txt')
    return jsonify(r)

@api.route('/get_vdr0200/<sn>/')    #50
def get_vdr0200(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/get_vdr0200.sh|sh')
    return jsonify(r)

@api.route('/get_drive_time/<sn>/')
def get_drive_time(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/get_drive_time.sh|sh')
    return jsonify(r)

@api.route('/get_driver_list/<sn>/')    #50
def get_driver_list(sn):
    r=utils.exec_command(sn, 'vcmd re_driver:')
    return jsonify(r)

@api.route('/get_vdr9101/<sn>/')    #50
def get_vdr9101(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/get_vdr9101.sh|sh')
    return jsonify(r)

################################## Operate VDR ##################################
@api.route('/opt_restart_vdr/<sn>/')
def opt_restart_vdr(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/opt_restart_vdr.sh | sh')
    return jsonify(r)

@api.route('/opt_tts_test/<sn>/')
def opt_tts_test(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/opt_tts_test.sh | sh')
    return jsonify(r)

@api.route('/opt_upvdr/<sn>/')    #OS40
def opt_upvdr(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/opt_upvdr.sh | sh')
    return jsonify(r)

@api.route('/opt_upvdr_beta/<sn>/')    #OS40
def opt_upvdr_beta(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/opt_upvdr_beta.sh | sh')
    return jsonify(r)

@api.route('/opt_vdr_server_config/<sn>/<paras>')
def vdr_server_config(sn,paras):
    opt_vdr_server_config_cmd='curl -s http://115.29.151.181/webtool/vdr/opt_vdr_server_config.sh | sh -s '+paras
    r=utils.exec_command(sn, opt_vdr_server_config_cmd)
    return jsonify(r)

@api.route('/opt_vdr1_plate_config/<sn>/<paras>') #OS40 Config Plate Number
def opt_vdr1_plate_config(sn,paras):
    opt_vdr1_plate_config_cmd='curl -s http://115.29.151.181/webtool/vdr/opt_vdr1_config_platenum.sh | sh -s '+paras
    r=utils.exec_command(sn, opt_vdr1_plate_config_cmd)
    return jsonify(r)

@api.route('/opt_vdr_plate_config/<sn>/<paras>') #OS50 Config Plate Number
def opt_vdr_plate_config(sn,paras):
    car_num = utf8_gb2312_hex(paras)
    car_num = complete_bite(24, car_num)
    my_car_num = ucivdr('0083', car_num)
    my_car_num = my_car_num+';uci -c /vdr/config commit vdr'
    r=utils.exec_command(sn, my_car_num)
    return jsonify(r)

@api.route('/opt_vdr_vin_config/<sn>/<paras>') #OS50 Config Vin Number
def opt_vdr_vin_config(sn,paras):
    vin_num = utf8_gb2312_hex(paras)
    my_vin_num = ucivdr('car_vin', vin_num)
    my_vin_num = my_vin_num+';uci -c /vdr/config commit vdr'
    r=utils.exec_command(sn, my_vin_num)
    return jsonify(r)

@api.route('/opt_vdr_plate_color_config/<sn>/<paras>') #OS50 Config Plate Color
def opt_vdr_plate_color_config(sn,paras):
    car_color=complete_bite(2,paras,'FALSE')
    my_car_color=ucivdr('0084',car_color)
    my_car_color = my_car_color+';uci -c /vdr/config commit vdr'
    r=utils.exec_command(sn, my_car_color)
    return jsonify(r)

@api.route('/opt_vdr2_speed_config/<sn>/<paras>') #OS50 Config Speed
def opt_vdr2_speed_config(sn,paras):
    car_max_speed = dectohex(paras)
    car_max_speed = complete_bite(8, car_max_speed, 'FALSE')
    my_car_max_speed = ucivdr('0055', car_max_speed)
    my_car_max_speed = my_car_max_speed+';uci -c /vdr/config commit vdr'
    r=utils.exec_command(sn, my_car_max_speed)
    return jsonify(r)

@api.route('/opt_vdr_night_speed/<sn>/') #OS50
def opt_vdr_night_speed(sn):
    r = utils.exec_command(sn, 'curl -s http://download.iovyw.com/webtool/vdr/opt_vdr_night_speed_on_off.sh|sh')
    return jsonify(r)

@api.route('/opt_add_mirror_config/<sn>/<paras>')
def add_mirror_config(sn,paras):
    opt_add_mirror_config_cmd = 'curl -s http://115.29.151.181/webtool/vdr/opt_add_mirror_config.sh | sh -s '+paras
    r=utils.exec_command(sn, opt_add_mirror_config_cmd)
    return jsonify(r)

@api.route('/opt_del_mirror_config/<sn>/<paras>')
def del_mirror_config(sn,paras):
    opt_del_mirror_config_cmd = 'curl -s http://115.29.151.181/webtool/vdr/opt_del_mirror_config.sh | sh -s '+paras
    r=utils.exec_command(sn, opt_del_mirror_config_cmd)
    return jsonify(r)

@api.route('/opt_del_backserver_config/<sn>/')
def opt_del_backserver_config(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/opt_del_backserver_config.sh | sh')
    return jsonify(r)

@api.route('/opt_vdr_log/<sn>/')
def opt_vdr_log(sn):
    r=utils.exec_command(sn, '')
    return jsonify(r)

@api.route('/opt_overtime_config/<sn>/')    #40
def opt_overtime_config(sn):
    r=utils.exec_command(sn, '')
    return jsonify(r)

@api.route('/opt_speed_tts/<sn>/')    #40
def opt_speed_tts(sn):
    r=utils.exec_command(sn, '')
    return jsonify(r)

@api.route('/opt_speed_limit_tts/<sn>/')    #40
def opt_speed_limit_tts(sn):
    r=utils.exec_command(sn, '')
    return jsonify(r)

@api.route('/opt_simno_config/<sn>/')
def opt_simno_config(sn):
    r=utils.exec_command(sn, '')
    return jsonify(r)

@api.route('/opt_private_config/<sn>/')    #50
def opt_private_config(sn):
    r=utils.exec_command(sn, '')
    return jsonify(r)

@api.route('/opt_vdr1_speed_config/<sn>/<paras>')
def opt_vdr1_speed_config(sn,paras):
    opt_vdr1_speed_cmd = 'curl -s http://115.29.151.181/webtool/vdr/opt_vdr1_config_speed.sh | sh -s ' + paras
    r=utils.exec_command(sn, opt_vdr1_speed_cmd)
    return jsonify(r)

@api.route('/opt_vdr_sim1_config/<sn>/<paras>')
def opt_vdr_sim1_config(sn,paras):
    mycmd = 'curl -s http://download.iovyw.com/webtool/vdr/opt_vdr1_common_config.sh | sh -s Sim ' + paras
    r=utils.exec_command(sn, mycmd)
    return jsonify(r)

@api.route('/opt_vdr_vin1_config/<sn>/<paras>')
def opt_vdr_vin1_config(sn,paras):
    mycmd = 'curl -s http://download.iovyw.com/webtool/vdr/opt_vdr1_common_config.sh | sh -s VinID ' + paras
    r=utils.exec_command(sn, mycmd)
    return jsonify(r)


@api.route('/opt_vdr_color1_config/<sn>/<paras>')
def opt_vdr_color1_config(sn,paras):
    mycmd = 'curl -s http://download.iovyw.com/webtool/vdr/opt_vdr1_common_config.sh | sh -s VinCR ' + paras
    r=utils.exec_command(sn, mycmd)
    return jsonify(r)

@api.route('/opt_vdr2_sim_config/<sn>/<paras>')
def opt_vdr2_sim_config(sn,paras):
    mysim = ucivdr('simno', paras)
    mysim = mysim + ';uci -c /vdr/config commit vdr'
    r = utils.exec_command(sn, mysim)
    return jsonify(r)

@api.route('/opt_print_test/<sn>/')    #50
def opt_print_test(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/opt_print_test.sh | sh')
    return jsonify(r)

@api.route('/opt_4g_upgrade/<sn>/')    #50
def opt_4g_upgrade(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/maintenance_script/upgrade/upgradeModem180228.sh | sh')
    return jsonify(r)

@api.route('/opt_tts_vol_config/<sn>/')    #50
def opt_tts_vol_config(sn):
    r=utils.exec_command(sn, 'curl -s http://115.29.151.181/webtool/vdr/opt_tts_vol_config.sh | sh')
    return jsonify(r)

@api.route('/<pro_id>/<pro_data>') #pro_test   http://0.0.0.0/api/8001/7e800100050130070661730000166b020000d97e
def analyse(pro_id,pro_data):
    r=utils.exec_analyse(pro_id,pro_data)
    print type(r)
    print r
    print jsonify(r)
    return jsonify(r)
@api.route('/17691/<pro_id>/<pro_data>') #pro_test   http://0.0.0.0/api/8001/7e800100050130070661730000166b020000d97e
def analyse17691(pro_id,pro_data):
    r=utils.exec_analyse_17691(pro_id,pro_data)
    print type(r)
    print r
    print jsonify(r)
    return jsonify(r)
@api.route('/hangbiao/<pro_id>/<pro_data>') #pro_test   http://0.0.0.0/api/8001/7e800100050130070661730000166b020000d97e
def analysehangbiao(pro_id,pro_data):
    r=utils.exec_analyse_hangbiao(pro_id,pro_data)
    print type(r)
    print r
    print jsonify(r)
    return jsonify(r)
@api.route('/upload/<filename>')
def api_upload(filename):
    print "api_upload start"
    file_dir=os.path.join(basedir,UPLOAD_FOLDER)
    print "file_dir=%s"%file_dir
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
   # f=request.files['myfile']  # 从表单的file字段获取文件，myfile为该表单的name值
    
   # if f and allowed_file(f.filename):  # 判断是否是允许上传的文件类型
    fname=secure_filename(filename)
    print fname
    ext = fname.rsplit('.',1)[1]  # 获取文件后缀
    unix_time = int(time.time())
    new_filename=str(unix_time)+'.'+ext  # 修改了上传的文件名
    filename.save(os.path.join(file_dir,new_filename))  #保存文件到upload目录
    token = base64.b64encode(new_filename)
    print token
 
    return jsonify({"errno":0,"errmsg":"上传成功","token":token})
    #else:
     #   return jsonify({"errno":1001,"errmsg":"上传失败"})

@api.route('/up_photo', methods=['POST'], strict_slashes=False)
def up_photo():
    file_dir = os.path.join(basedir,UPLOAD_FOLDER)
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    f = request.files['photo']
    if f and allowed_file(f.filename):
        fname = secure_filename(f.filename)
        ext = fname.rsplit('.', 1)[1]
        new_filename = Pic_str().create_uuid() + '.' + ext
        print new_filename
        f.save(os.path.join(file_dir, new_filename))
        return jsonify({"success": 0, "msg": "上传成功"})
    else:
        return jsonify({"error": 1001, "msg": "上传失败"})

@api.route('/down_photo/<string:filename>', methods=['GET'])
def down_photo(filename):
    if request.method == "GET":
        if os.path.isfile(os.path.join('upload', filename)):
            return send_from_directory('upload', filename, as_attachment=True)
        pass

@api.route('/show_photo/<string:filename>', methods=['GET'])
def show_photo(filename):
    file_dir = os.path.join(basedir,UPLOAD_FOLDER)
    print"show_photo file_dir=%s,filename=%s"%file_dir
    print"show_photo filename=%s"%filename
    if request.method == 'GET':
        if filename is None:
            pass
        else:
            image_data = open(os.path.join(file_dir, '%s' % filename), "rb").read()
            response = make_response(image_data)
            response.headers['Content-Type'] = 'image/png'
            return response
    else:
        pass
